package com.smart.common;


import com.smart.common.enums.ErrorCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * 响应模型
 * @param <T>
 */
@Data
@ApiModel("响应模型")
public class WebResponse<T> implements Serializable {
    private static final long serialVersionUID = -6363017973740203418L;
    public static final String STATUS_SUCCESS = "success";
    public static final String STATUS_FAIL = "fail";

    /** 响应码 */
    @ApiModelProperty("响应码")
    private String code;
    /** 响应状态 */
    @ApiModelProperty("响应状态")
    private String status;
    /** 响应数据 */
    @ApiModelProperty("响应数据")
    private T data;
    /** 响应消息 */
    @ApiModelProperty("响应消息")
    private String message;
    /** 时间戳 */
    @ApiModelProperty("时间戳")
    private long time = System.currentTimeMillis();

    public WebResponse(String code, String msg) {
        this.code = code;
        this.status = STATUS_FAIL;
        this.message = msg;
    }

    public WebResponse(ErrorCode errorCode) {
        this.code = errorCode.getCode();
        this.status = STATUS_FAIL;
        this.message = errorCode.getMsg();
    }

    public static WebResponse build(String code, String msg) {
        return new WebResponse(code, msg);
    }

    public static <T> WebResponse build(T data) {
        return new WebResponse(data);
    }

    public static <T> WebResponse build(T data, String msg) {
        return new WebResponse(data, msg);
    }

    public WebResponse(ErrorCode errorCode, String msg) {
        this.code = errorCode.getCode();
        this.status = STATUS_FAIL;
        this.message = errorCode.getMsg() + ": " +msg;
    }

    public WebResponse(T data, String msg) {
        this.code = "200";
        this.status = STATUS_SUCCESS;
        this.message = msg;
        this.data = data;
    }

    public WebResponse(T data) {
        this.code = "200";
        this.status = STATUS_SUCCESS;
        this.message = "成功";
        this.data = data;
    }

    public boolean isSuccess() {
        return Objects.equals(this.code, "200");
    }
}
